from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.filters import OrderingFilter, SearchFilter
from .paginations import CoursePageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend

from . import serializers, models
from .filters import CourseFilterSet


class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer

    # 配置过滤器
    filter_backends = [OrderingFilter, SearchFilter]
    # 参与排序的字段
    ordering_fields = ['price', 'id', 'students']
    # 参与搜索的字段
    search_fields = ['name', 'brief']
    # 参与分类筛选的字段：所有的字段都可以，但是用于分组的字段更有意义
    filter_class = CourseFilterSet

    # 分页器
    pagination_class = CoursePageNumberPagination


class CategoryListAPIView(ListAPIView):
    queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders').all()
    serializer_class = serializers.CategoryModelSerializer


class FreeCourseRetrieveAPIView(RetrieveAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer


class ChapterListAPIView(ListAPIView):
    queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.CourseChapterModelSerializer

    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']
